package com.example.matchingengine.config;

import com.example.matchingengine.model.Order;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 对象池配置类
 * 使用Apache Commons Pool2实现对象池，减少GC压力
 */
@Configuration
public class ObjectPoolConfig {

    @Value("${matching-engine.object-pool.max-total}")
    private int maxTotal;

    @Value("${matching-engine.object-pool.max-idle}")
    private int maxIdle;

    @Value("${matching-engine.object-pool.min-idle}")
    private int minIdle;

    /**
     * 订单对象池
     */
    @Bean
    public GenericObjectPool<Order> orderPool() {
        GenericObjectPoolConfig<Order> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setJmxEnabled(false);  // 禁用JMX监控避免注册冲突
        return new GenericObjectPool<>(new OrderFactory(), poolConfig);
    }

    /**
     * 订单对象工厂
     */
    private static class OrderFactory extends BasePooledObjectFactory<Order> {

        @Override
        public Order create() {
            return new Order();
        }

        @Override
        public PooledObject<Order> wrap(Order order) {
            return new DefaultPooledObject<>(order);
        }

        @Override
        public void passivateObject(PooledObject<Order> pooledObject) {
            // 对象归还池时重置状态
            pooledObject.getObject().reset();
        }
    }
}